package com.yc.service.impl;


import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.yc.config.AliyunOssProperties;
import com.yc.config.OssConfig;
import com.yc.service.OssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@EnableConfigurationProperties(AliyunOssProperties.class)
@Import(value = {OssConfig.class})
public class OssfileServiceImpl implements OssFileService {

    private final OSS ossClient;

    private final String endpoint;
    private final String bucketName;

    // 访问路径前缀
    private final String UrlPrefix;

    @Autowired
    public OssfileServiceImpl(AliyunOssProperties aliyunOssProperties, OSS ossClient) {
        this.ossClient = ossClient;
        this.endpoint = aliyunOssProperties.getEndpoint();
        this.bucketName = aliyunOssProperties.getBucketName();

        UrlPrefix = "https://jxqandchx.cn/";
    }

    @Override
    @Async
    public CompletableFuture<String> uploadFile(MultipartFile file,String prefix) {
        if (ossClient == null) {
            throw new IllegalStateException("OSS 未初始化");
        }
        return CompletableFuture.supplyAsync(() -> {
            String originalFilename = file.getOriginalFilename();
            String filename = null;
            // 生成唯一的文件名
            if (originalFilename != null) {
                filename = uniqueName(originalFilename);
            }
            String objectName = filename;
            if (prefix!=null){
                 objectName = prefix + "/"+filename;
            }

            try (InputStream inputStream = file.getInputStream()) {
                ossClient.putObject(bucketName, objectName, inputStream);
            } catch (IOException e) {
                log.error("Failed to upload file: {}", originalFilename, e);
                throw new RuntimeException("Failed to upload file", e);
            }
            return UrlPrefix+objectName;
        });
    }


    @Async
    public CompletableFuture<String> uploadFile(MultipartFile file) {
        // 获取文件名
        String filename = file.getOriginalFilename();

        // 检查文件名是否为空
        if (filename == null || filename.isEmpty()) {
            throw new IllegalArgumentException("File name is empty");
        }
        // 获取文件后缀
        String prefix = filename.substring(filename.lastIndexOf("."));
        return uploadFile(file,prefix);
    }

    @Override
    public List<String> uploadFile(MultipartFile[] files) {
        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (MultipartFile file : files) {
            futures.add(uploadFile(file));
        }
        return futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
    }

    @Override
    public String uploadFile(String prefix, String filename, InputStream inputStream, boolean useUuid) {
        // 根据 useUuid 参数决定是否生成唯一的文件名
        if (useUuid) {
            if (filename != null) {
                // 生成唯一文件名
                filename = uniqueName(filename);
            }
        }
        //文件存放路径
        String objectName = prefix + "/" + filename;
        //上传文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
        ossClient.putObject(putObjectRequest);
        //返回文件路径

        return UrlPrefix+ objectName;
    }


    @Override
    public String uploadFile(String prefix, String filename, InputStream inputStream) {
        return uploadFile(prefix, filename, inputStream, true);
    }

    @Override
    public String uploadFile(String filename, InputStream inputStream){
        //如果前缀名为空,则取出文件后缀作为文件存放的路径
        String prefix = filename.substring(filename.lastIndexOf("."));
        return uploadFile(prefix, filename, inputStream, true);
    }
    public String uniqueName(String filename){
        return UUID.randomUUID().toString().replaceAll("-", "") + filename;
    }

    public void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

}
